// 数据库审计功能测试脚本

async function testDatabaseAudit() {
  console.log('🚀 开始测试数据库审计功能...');
  
  try {
    // 1. 检查审计表是否存在
    console.log('\n1. 检查审计表是否存在...');
    
    const checkAuditTableResponse = await fetch('http://localhost:3001/api/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sql: "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%audit%'"
      })
    });
    
    if (checkAuditTableResponse.ok) {
      const result = await checkAuditTableResponse.json();
      console.log('✅ 审计表查询成功');
      
      if (result.data && result.data.length > 0) {
        console.log('📋 审计相关表:');
        result.data.forEach(table => {
          console.log(`  - ${table.name}`);
        });
      } else {
        console.log('⚠️ 未找到审计相关表');
      }
    } else {
      console.error('❌ 审计表查询失败:', checkAuditTableResponse.status);
    }
    
    // 2. 检查触发器是否存在
    console.log('\n2. 检查触发器是否存在...');
    
    const checkTriggersResponse = await fetch('http://localhost:3001/api/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sql: "SELECT name FROM sqlite_master WHERE type='trigger'"
      })
    });
    
    if (checkTriggersResponse.ok) {
      const result = await checkTriggersResponse.json();
      console.log('✅ 触发器查询成功');
      
      const auditTriggers = result.data.filter(trigger => 
        trigger.name.includes('tasklist') && trigger.name.includes('audit')
      );
      
      if (auditTriggers.length > 0) {
        console.log('📋 审计相关触发器:');
        auditTriggers.forEach(trigger => {
          console.log(`  - ${trigger.name}`);
        });
      } else {
        console.log('⚠️ 未找到审计相关触发器');
      }
    } else {
      console.error('❌ 触发器查询失败:', checkTriggersResponse.status);
    }
    
    // 3. 创建一个测试任务并检查审计记录
    console.log('\n3. 创建测试任务并检查审计记录...');
    
    // 创建测试任务
    const testTask = {
      Task_No: 'TEST001',
      Job_Style: '测试类型',
      Unload_Line: 1,
      Unload_Col: 2,
      Unload_Layer: 3,
      is_issued: 0
    };
    
    const createTaskResponse = await fetch('http://localhost:3001/api/tasks', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(testTask)
    });
    
    if (createTaskResponse.ok) {
      const createResult = await createTaskResponse.json();
      console.log('✅ 测试任务创建成功');
      console.log('  任务ID:', createResult.data?.taskId || 'N/A');
      
      // 等待一段时间让触发器执行
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 查询审计记录
      console.log('\n4. 查询审计记录...');
      const queryAuditResponse = await fetch('http://localhost:3001/api/query', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
      },
        body: JSON.stringify({
          sql: "SELECT * FROM tasklist_audit ORDER BY changed_at DESC LIMIT 5"
        })
      });
      
      if (queryAuditResponse.ok) {
        const auditResult = await queryAuditResponse.json();
        console.log('✅ 审计记录查询成功');
        
        if (auditResult.data && auditResult.data.length > 0) {
          console.log('📋 最近的审计记录:');
          auditResult.data.forEach((record, index) => {
            console.log(`  ${index + 1}. 任务ID: ${record.task_id}, 类型: ${record.change_type}, 状态: ${record.old_is_issued} -> ${record.new_is_issued}, 时间: ${record.changed_at}`);
          });
        } else {
          console.log('📋 暂无审计记录');
        }
      } else {
        console.error('❌ 审计记录查询失败:', queryAuditResponse.status);
      }
    } else {
      console.error('❌ 测试任务创建失败:', createTaskResponse.status);
    }
    
    console.log('\n✅ 数据库审计功能测试完成');
  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error);
  }
}

// 运行测试
testDatabaseAudit();